<template>
  <div>
    <t-adaptive-page
        class="menu_mange"
        tableTitle="订单列表"
        ref="TAdaptivePageDemo"
        isCopy
        show-summary
        :table="state.table"
        :row-key="getRowKey"
        :height="260"
        :columns="state.table.columns"
        :opts="opts"
        isExpansion
        :isTTableSelfFilling="false"
        isShowWidthSize
        :widthSize="4"
        @size-change="handlesSizeChange"
        @page-change="handlesCurrentChange"
        @selection-change="selectionChange"
        @submit="conditionEnter"
    >
      <template #nickName="{ scope }">
        <div>{{ scope.row.nickName }}</div>
      </template>
      <template #ddate="{scope}">
        <el-text type="primary">{{ parseTime(scope.row.ddate, '{y}-{m}-{d}' ) }}</el-text>
      </template>
      <template #footerBtn>

        <el-button type="primary" :disabled="!state.idds.length" @click="addTableDatas">确定选择</el-button>
        <el-button type="primary" @click="TAdaptivePageDemo.TQueryConditionPage.checkHandle()">查询</el-button>
        <el-button type="danger" @click="TAdaptivePageDemo.TQueryConditionPage.resetHandle()">重置</el-button>
      </template>


    </t-adaptive-page>
    <t-table
        title="明细"
        show-summary
        :table="state.table_d"
        :columns="state.table_d.columns"
        :isShowPagination="false"
        ref="singleReferEditTSelectTable"
        :listTypeInfo="state.listTypeInfo"
        @handleEvent="handleEvent"
        @selection-change="selectionDChange"
        @validateError="validateError"
    >
      <template #toolbar>
        <span>已选择 {{state.idds.length}} 条数据,合计{{ state.sum}}</span>
      </template>
      <!-- 自定义单元格编辑组件(多选下拉选择) -->
      <template #editHobby="{ scope }">
        <el-select
            v-if="state.addDialog.formData.cCusCode"
            v-model="scope.row[scope.column.property]"
            filterable
            remote
            reserve-keyword
            placeholder="请输入存货名称或编码"
            remote-show-suffix
            :remote-method="remoteMethod"
            :loading="state.loading"
            @change="e => updateInv(e, scope.row)"
            style="width: 100%"
        >
          <el-option
              v-for="item in state.options"
              :key="item.id"
              :label="item.id"
              :value="item.id"
          >
            <span style="float: left">{{ item.name }}</span>
            <span
                style="float: right; color: var(--el-text-color-secondary); font-size: 13px"
            >
                        {{ item.id }}
                      </span>
          </el-option>
        </el-select>
      </template>
    </t-table>
  </div>

</template>

<script setup lang="tsx" name="selection">
import { computed, onMounted, reactive, ref, toRefs } from 'vue'
import { debounce, parseTime,dateDiff } from '@/utils/util'
import { cubasdocStore } from '@/stores/modules/cubasdoc'
import { getContractInfo, getContractList, findbaseBasicManage, findBoxData } from '@/api/base'
import { salesOrderAdd, salesOrderList, ComboBoxDataList,salesOrderListDetails,salesOrderDelete,salesOrderCheck,salesOrderUnCheck,salesOrderClose,SalesChangeOrder } from '@/api/sale_order'
import { ElMessage, ElMessageBox } from 'element-plus'

const emit = defineEmits(['changeTables'])
// 获取ref
const TAdaptivePageDemo: any = ref(null)

// 选择复选框
const selectionChange = (val: any) => {

  let isCheck =  0

  //判断同一公司及同一联系人才能合并发货
  if (state.chooseModel.length > 1) {
    let company = state.chooseModel[0].cCusCodeID
    let person = state.chooseModel[0].contacts
    for (let i = 0; i < val.length; i++) {
      if (company != val[i].cCusCodeID || person != val[i].contacts) {
        isCheck++
        ElMessage.error('同一客户同一联系人才能合并发货')
        TAdaptivePageDemo.value!.toggleRowSelection(val[i], false)
      }
    }
  }
  if (isCheck == 0)
    state.chooseModel = val
  state.ids = val.map((item: any) => item.Sid)

  let join = '';
  if (state.ids.length == 1){
    join = state.ids[0]+','
  }else {
    join = state.ids.join(',')
  }
  //查询物料详情
  salesOrderListDetails({
    Sid: join,
    selectvalue: 'undefined',
    value: 'undefined',
    WF: '',
    table: 'SalesOrderView',
    sortorder: 'asc'
  }).then((res) => {

    state.table_d.data = res.Rows.filter((item) => item.NotFHquantity >0 && item.Xingguan === '否' && item.iTaxUnitPrice>0)
  })


}

// 翻页选中的唯一值
const getRowKey = row => {
  return row.Sid
}

const addTableDatas = (row) => {

  emit('changeTables', state.idds, state.chooseModel[0])
  TAdaptivePageDemo.value.clearSelection()
  state.idds=[]
  state.chooseModel=[]
  state.table_d.data=[]
  state.table.data=[]
}

const selectionDChange = (row) => {
  state.idds = row
  state.sum = 0

  //求和未发货数量
  state.idds.forEach((item) => {
    state.sum += item.NotFHquantity
  })
}

const editDel = (item, index, row) => {
  //
  row.splice(index, 1)

}

const state: any = reactive({
  ids: [],
  idds:[],
  sum:0,
  chooseModel:[],
  invOptions: [],
  queryData: {
    StateID:'已审核'
  },
  table: {
    border: true,
    firstColumn: { type: 'selection', fixed: true,isPaging: true},
    currentPage: 1,
    pageSize: 10,
    total: 0,
    // 接口返回数据
    data: [],
    // 表头数据
    columns: [
      { prop: 'SalesType', label: '销售类型' },
      {
        prop: 'repair',
        label: '是否补录',
      },
      { prop: 'TranType', label: '交易类型' },
      { prop: 'SalesCode', label: '销售订单号' },
      { prop: 'ddate', label: '单据日期',slotName: 'ddate', },
      { prop: 'StateID', label: '单据状态' },
      // { prop: 'createTime', label: '部门编码' },
      { prop: 'cDepName', label: '部门' },
      // { prop: 'createTime', label: '业务员编码' },
      { prop: 'cPsn_Name', label: '业务员' },
      { prop: 'cCusCodeID', label: '客户编码' },
      { prop: 'cCusName', label: '客户名称' },
      { prop: 'address', label: '客户地址' },
      { prop: 'contacts', label: '客户联系人' },
      { prop: 'Telephone', label: '联系电话' },
      { prop: 'change', label: '是否正在变更' },
      { prop: 'remarks', label: '备注',showOverflowTooltip: true },
      { prop: 'Preparer', label: '操作人' },

      { prop: 'Pdate', label: '操作时间' },
    ],
  },
  addDialog: {
    title: '新增',
    visible: false,
    loading: false,
    formData: {
      ddate: parseTime(new Date(), '{y}-{m}-{d}'),
      // BodyJson:[],
      taxrate: 13,
      repair: '否',
      SalesType: '分期付款',
      TranType: '分期付款',
      salesman: '101',
      cDepName: '推广服务部',
      depcode: '05',
      contacts: '王晓峰',
      Telephone: '13323334545',
      DeliveryMethod: '快递',
      PackingMethod: '自备包装',
      remarks: '客户要求私密发货',
      ExchangeRate: 6.5,
      Pdate: parseTime(new Date(), '{y}/{m}/{d} {h}:{i}:{s}'),
      Preparer: '邹涛',
      change: '否',
      StateID: '自由',
    },
    rules: {
      cCusCode: [{ required: true, message: '请选择客户', trigger: 'change' }],
      ContractNo: [{ required: true, message: '请选择合同号', trigger: 'blur' }],
      repair: [{ required: true, message: '请选择是否补录', trigger: 'change' }],
      SalesType: [{ required: true, message: '请选择销售类型', trigger: 'change' }],
      // SalesCode: [{ required: true, message: "请输入销售订单号", trigger: "blur" }],
      TranType: [{ required: true, message: '请选择交易类型', trigger: 'change' }],
      ddate: [{ required: true, message: '请选择单据时间', trigger: 'change' }],
      salesman: [{ required: true, message: '请选择业务员', trigger: 'change' }],

      taxrate: [{ required: true, message: '请输入税率', trigger: 'blur' }],
      ExchangeRate: [{ required: true, message: '请输入汇率', trigger: 'blur' }]
    }
  },
  table_d: {
    rules: {},
    firstColumn: { type: 'selection', fixed: true },
    data: [],
    columns: [
      {
        prop: 'rowno',
        label: '序号',
        sortable: true,
      },
      {
        prop: 'cInvCode',
        label: '存货编码',
        placeholder: '请选择存货',
        minWidth: '120',
        sortable: true,

      },
      {
        prop: 'cInvName',
        label: '存货名称',
        minWidth: '200',
      },
      {
        prop: 'cInvStd',
        minWidth: '120',
        label: '规格型号',
      },

      {
        prop: 'cInvCodeK',
        minWidth: '120',
        label: '客户存货编码',
        sortable: true,
      },

      {
        prop: 'cInvNameK',
        minWidth: '120',
        label: '客户存货名称',
      },
      {
        prop: 'cInvStdK',
        minWidth: '160',
        label: '客户存货规格型号',
      },

      {
        prop: 'iTaxUnitPrice',
        label: '含税单价',
        sortable: true,
        minWidth: '120',
      },
      {
        prop: 'UnitPrice',
        label: '无税单价',
        minWidth: '120',
        sortable: true,
      },

      {
        prop: 'NotFHquantity',
        label: '未发货数量',
        minWidth: '120',
        sortable: true,
      },
      {
        prop: 'quantity',
        label: '数量',
        minWidth: '100',
        sortable: true,
      },
      {
        prop: 'taxRate',
        label: '税率',
        minWidth: '180',
      },

      {
        prop: 'deliver',
        minWidth: '160',
        sortable: true,
        label: '初始预发货日期',
      },
      {
        prop: 'deliverDate',
        minWidth: '160',
        sortable: true,
        label: '实际预发货日期',
      },
      {
        prop: 'Xingguan',
        minWidth: '160',
        label: '是否关闭',

      },

      {
        prop: 'MOQ',
        minWidth: '160',
        label: '订单MOQ',
      },

      {
        prop: 'DeliveryTime',
        minWidth: '160',
        label: '客户停产日期',
      },

      {
        prop: 'MinimumTime',
        minWidth: '160',
        label: '最短交期(天)',
      },

      {
        prop: 'MaterialShutdown',
        minWidth: '160',
        label: '物料停产日期',
      },
      {
        prop: 'SafetyStock',
        minWidth: '180',
        label: '安全库存量',
      },
      {
        prop: 'TransitionStatus',
        minWidth: '160',
        label: '转产状态',
      },
      {
        prop: 'makeUp',
        label: '拼板数',
        // headerRequired: true,
        minWidth: '180',
      },

      {
        prop: 'completeDate',
        minWidth: '160',
        sortable: true,
        label: '预生产完工日期',
      },
      {
        prop: 'cycle',
        minWidth: '180',
        label: '日均产量',
      },
      {
        prop: 'Productivity',
        minWidth: '160',
        label: '产品难度系数',
      },

      {
        prop: 'ActualCycle',
        minWidth: '160',
        label: '标准产品产能',
      },
      {
        prop: 'ActualCycleJ',
        minWidth: '160',
        label: '交付日总产能',
      },
      {
        prop: 'CustomerOrder',
        minWidth: '160',
        sortable: true,
        label: '客户订单号',
      },

      {
        prop: 'remarks',
        minWidth: '160',
        label: '备注',
      },
      // {
      //   prop: 'ContractID',
      //   minWidth: '160',
      //   label: '标的ID',
      // },
      {
        prop: 'ContractNo',
        minWidth: '160',
        label: '合同号',
      }
    ],
    // 表格内操作列
  },
  userList: [],
  invList: [],
})

const opts = computed(() => {
  return {
    SalesCode: {
      label: '销售订单号',
      comp: 'el-input'
    },
    // cInvCode: {
    //   label: '存货信息',
    //   placeholder: '请选择存货',
    //   comp: 't-select',
    //   isSelfCom: true,
    //   bind: {
    //     valueCustom: 'id',
    //     labelCustom: 'name',
    //     optionSource: state.invOptions
    //   }
    // },
    cCusCode: {
      label: '客户',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'cCusCode',
        labelCustom: 'ccusname',
        optionSource: cubasdoc.data
      }
    },

    salesman: {
      label: '业务员',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'cPsn_Num',
        labelCustom: 'cPsn_Name',
        optionSource: state.userList
      }
    },
    dbdate: {
      label: '制单时间',
      comp: 'el-date-picker',
      span: 1,
      event: 'date',
      bind: {
        rangeSeparator: '-',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        valueFormat: 'YYYY-MM-DD',
        type: 'daterange'
      }
    },
    FHZX: {
      label: '执行情况',
      comp: 't-select',
      isSelfCom: true,
      bind: {
        valueCustom: 'value',
        labelCustom: 'label',
        optionSource: [
          {
            label: '发货已完成',
            value: '发货已完成'
          },
          {
            label: '发货未完成',
            value: '发货未完成'
          }
        ]
      }
    }
  }
})
// 最终参数获取
const getQueryData = computed(() => {
  let queryList = []
  const res = toRefs(state.queryData)
  Object.keys(res).forEach(item => {

    let data = {}
    if (res[item].value) {
      if (item === 'dbdate') {
        data = {
          field:'Pdate',
          op:'and',
          value:res[item].value[0],
          type:'date'
        }
        queryList.push(data)
        data = {
          field:'Pdateend',
          op:'and',
          value:res[item].value[1],
          type:'date'
        }
        queryList.push(data)
      } else {
        data = {
          field:item,
          op:'and',
          value:res[item].value,
          type:'text'
        }
        queryList.push(data)
      }
    }
  })
  queryList.push({
    field:'StateID',
    op:'and',
    value:'已审核',
    type:'text'
  })
  queryList.push({
    field:'Type',
    op:'and',
    value:'0',
    type:'text'
  })

  return queryList.length > 0 ? { rules:queryList,op:"and" }:null
})
// 点击查询按钮
const conditionEnter = (data: any) => {

  state.queryData = data
  getData()
}
onMounted(() => {

  getUserList()
  getInvList()
  findContracts()
  getData()
})
// 获取菜单数据
const getData = async () => {
  let queryData = {
    table: 'SalesOrderView',
    name: 'cDepName like',
    value: '销售部',
    DoType: 0,
    KJTJ: ''
  }
  if (getQueryData.value) {

    queryData.KJTJ = JSON.stringify(getQueryData.value)
  }
  const formData = new FormData()
  formData.append('page', state.table.currentPage) // 添加字段
  formData.append('pagesize', state.table.pageSize) // 添加另一个字段
  const { Rows,Total } = await salesOrderList(queryData, formData)
  state.table.data = Rows
  state.table.total = Total
}
// 页面大小
const handlesSizeChange = (val: any) => {
  state.table.pageSize = val
  getData()
}
// 页码
const handlesCurrentChange = (val: any) => {
  state.table.currentPage = val
  getData()
}

const singleReferEditTSelectTable: any = ref(null)

const cubasdoc = cubasdocStore()
//选择项
const cusoptions = ref(cubasdoc.data)


// 编辑单元格监听事件
const handleEvent = (type, val, index) => {

}

// 错误校验提示
const validateError = list => {
  list.map(val => {
    setTimeout(() => {
      ElMessage.error(`${val}是必填项！`)
    }, 100)
  })
}

function addOneTable() {
  state.table_d.data.push({
    //获取最大行号加1
    // LineNum: state.table.data.length + 1,
  })
}

//查询存货 -- 增加防抖函数
const remoteMethod = debounce(
  async query => {
    if (query) {
      state.loading = true
      state.loading = false

      let invData = {
        Code: query
      }
      //let { Data } = await GetInventory2(invData)
      //state.invList = Data
      state.options = state.invList.filter(item => {
        return (
          item.name.toLowerCase().includes(query.toLowerCase()) ||
          item.id.toLowerCase().includes(query.toLowerCase())
        )
      })
    } else {
      state.options = state.invList
    }
  },
  200,
  false
)

//存货选择
async function updateInv(e, row) {

  //过滤客户
  let invoptions = state.invList.filter(its => {
    return its.id.toLowerCase().includes(e.toLowerCase())
  })[0]
  if (invoptions) {
    //赋值
    row.cInvName = invoptions.name

    //row.Unit = invoptions.cComUnitCode 05191025  D080000141
  }
  //let response = await findListwldza({ cInvCode: e, cCusCode: state.addDialog.formData.CustCode })

}

//获取人员档案
const getUserList = async () => {
  let data = {
    page: 1,
    pagesize: 100000
  }
  let sqlString = {
    sqlString:
      'select cPsn_Name,cPsn_Num,cDept_num,cDepName from hr_hi_person p left join Department d on p.cDept_num = d.cDepCode'
  }

  let { Rows } = await findbaseBasicManage(data, sqlString)

  state.userList = Rows

}

function changeSalesman(e) {
  //过滤客户
  let useroptions = state.userList.filter(its =>
    its.cPsn_Num.toLowerCase().includes(e.toLowerCase())
  )
  if (useroptions) {
    //赋值
    state.addDialog.formData.cDepName = useroptions[0].cDepName
    state.addDialog.formData.depcode = useroptions[0].cDept_num
  }
}

//查询存货信息
const getInvList = async () => {
  let Rows = await findBoxData()
  state.invList = Rows


  state.invOptions = await ComboBoxDataList()
}

// 数量change事件
const numChange = (val, prop, scope) => {
  // let rate = (state.clumTable.data[scope.$index].Rate /100) + 1
  //
  // state.clumTable.data[scope.$index].Amount= (Number(state.clumTable.data[scope.$index].quantity || 0) * Number(state.clumTable.data[scope.$index].UnitPrice || 0)).toFixed(2)//含税金额
  // state.clumTable.data[scope.$index].UnitPrice=(Number(state.clumTable.data[scope.$index].Price || 0) / rate).toFixed(5)//不含税单价=含税单价 / 1.13
}

//查询合同详细信息
async function findContractInfo(id) {
  let { Data } = await getContractInfo({ id: id })
  if (Data?.SubList2) {
    //赋值合同明细
    state.table_d.data = Data.SubList2.map(item => {
      return {
        cInvName: item.CinvName,
        cInvCode: item.CinvCode,
        cInvStd: item.CinvAdd,

        quantity: item.Quantity,
        UnitPrice: item.Price,
        ContractID: item.Id,
        ContractNo: Data.Main.ContractNum,
        taxRate: Data.Main.Rate,
        // deliver:parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
        //deliverDate:"2024-08-15T16:00:00.000Z",
        // MaterialShutdown:"1753-01-01 00:00:00",
        // DeliveryTime:"1753-01-01 00:00:00",
        upgrade: '是'
      }
    })

  }
}

//查询合同信息
async function findContracts() {
  let queryData = {
    ContractType: null,
    CustCode: null,
    CustName: null,
    ContractNum: null,
    CreateFrom: null,
    CreateTo: null,
    Type: null,
    CreateBy: null
  }
  //获取合同信息
  let contractData = await getContractList(queryData)
  cubasdoc.setContractList(contractData.Data)
}

</script>
